const fs = require("fs");
const path = require("path");

const notes = {};

fs.readdirSync(__dirname).forEach((f) => {
  if (
    !f.startsWith(".") &&
    fs.statSync(path.join(__dirname, f)).isDirectory()
  ) {
    notes[f] = fs
      .readdirSync(path.join(__dirname, f))
      .filter((f) => f.endsWith(".md"))
      .sort((m, n) => parseInt(m) - parseInt(n))
      .map((subfile) => {
        let title = fs.readFileSync(path.join(__dirname, f, subfile), "utf-8");

        return `[${title
          .substr(0, title.indexOf("\n") + 1)
          .trim()
          .replace("# ", "")}](./${f}/${subfile})`;
      });
  }
});

let markdown = "";

for (let k in notes) {
  markdown += `# ${k}\n\n`;
  markdown += notes[k].map((t, i) => `${i + 1}. ${t}`).join("\n");
}
fs.writeFileSync(path.join(__dirname, "README.md"), markdown, "utf-8");
